package com.t2t.top.framework.util;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Spring Resource资源流处理；通过classpath/file/net获取文件等
 *
 * @author yangpengfei
 */
public class ResourceUtils {

    private static PathMatchingResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();

    public static Resource getResource(String locationPattern) {
        try {
            Resource[] resources = resourceLoader.getResources(locationPattern);
            return (resources != null && resources.length > 0) ? resources[0] : null;
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static Resource[] getResources(String locationPattern) {
        return getResources(locationPattern, false);
    }

    public static Resource[] getResources(String locationPattern, boolean ignoreFileNotFound) {
        try {
            return resourceLoader.getResources(locationPattern);
        } catch (FileNotFoundException e) {
            if (ignoreFileNotFound) {
                return null;
            }
            throw new IllegalArgumentException(e);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static Resource[] getResources(String[] locationPatterns) {
        return getResources(locationPatterns, false);
    }

    /**
     * 根据locationPatterns路径通配符获取Resource列表
     *
     * @param locationPatterns
     * @param ignoreFileNotFound true：抓不到文件时返回null， false：抛出文件找不到异常
     * @return Resource[]
     */
    public static Resource[] getResources(String[] locationPatterns, boolean ignoreFileNotFound) {
        List<Resource> resourceList = new ArrayList<Resource>();
        for (String locationPattern : locationPatterns) {
            Resource[] resources = getResources(locationPattern, ignoreFileNotFound);
            if (resources != null && resources.length > 0) {
                for (Resource resource : resources) {
                    resourceList.add(resource);
                }
            }
        }
        return resourceList.toArray(new Resource[]{});
    }
}